What is extendable-error?
The extendable-error npm package provides a simple way to create custom error classes in JavaScript by extending the built-in Error class. This is useful for creating more specific error types in your applications, which can help with error handling and debugging.
What are extendable-error's main functionalities?
Creating a Custom Error Class
This feature allows you to create a custom error class by extending the ExtendableError class. The custom error class can have its own name and additional properties or methods if needed.
class MyCustomError extends ExtendableError {
constructor(message) {
super(message);
this.name = 'MyCustomError';
}
}
try {
throw new MyCustomError('Something went wrong!');
} catch (error) {
console.error(error.name); // MyCustomError
console.error(error.message); // Something went wrong!
console.error(error.stack); // Stack trace
}
Handling Custom Errors
This feature demonstrates how to handle custom errors by checking the instance of the error. This allows for more specific error handling logic based on the type of error.
class DatabaseError extends ExtendableError {
constructor(message) {
super(message);
this.name = 'DatabaseError';
}
}
try {
throw new DatabaseError('Database connection failed!');
} catch (error) {
if (error instanceof DatabaseError) {
console.error('A database error occurred:', error.message);
} else {
console.error('An unknown error occurred:', error.message);
}
}
Other packages similar to extendable-error
custom-error-generator
The custom-error-generator package provides a way to create custom error classes with additional properties and methods. It is similar to extendable-error but offers more flexibility in defining custom error properties.
es6-error
The es6-error package is another library for creating custom error classes by extending the built-in Error class. It is similar to extendable-error but focuses on providing a minimal and straightforward approach to creating custom errors.
verror
The verror package allows for the creation of custom error classes with support for error wrapping and nested errors. It provides more advanced features compared to extendable-error, making it suitable for complex error handling scenarios.
Extendable Error
A simple abstract extendable error class that extends Error
, which handles the error name
, message
and stack
property.
Install
npm install extendable-error --save
Usage
import ExtendableError from 'extendable-error';
class SomeError extends ExtendableError {
constructor(
message: string,
public code: number
) {
super(message);
}
}
let someError = new SomeError('Some error', 0x0001);
License
MIT License.